package com.stanwind.aspect;

import com.stanwind.api.Log;
import com.stanwind.api.TokenUtils;
import com.stanwind.constant.ResponseState;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by StanWind on 2017/2/15.
 */
//越小优先级越高
@Order(1)
@Component
@Aspect
public class VerificationAspect {
    @Autowired
    private Log log;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 定义切点表达式
     */
    @Pointcut("execution(* com.stanwind.controller.game.*Controller.*(..))")
    public void pointCut() {
    }


    /**
     * d
     * 进行token的有效验证
     */
    @Around("pointCut()")
    public @ResponseBody Object verifyToekn(ProceedingJoinPoint proceedingJoinPoint) {

        String methodName = proceedingJoinPoint.getSignature().getName();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        HttpServletResponse response = servletWebRequest.getResponse();
        String token = request.getParameter("token");
        log.getLogger().info("Verify Aspect method->"+methodName+" token->"+token);

        Object result = null;
        try {
            //前置通知
            if (token == null || !tokenUtils.checkToken(token))
                return ResponseState.VERIFY_FAIL.convertToJsonObject();

            result = proceedingJoinPoint.proceed();
            //验证后自动延期
            tokenUtils.delayTokenDeadline(token);
            //返回通知
        } catch (Throwable throwable) {
            //异常通知
            throwable.printStackTrace();
        }
        //后置通知
        return result;




    }
}
